package cn.tedu.web.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 邮件发送测试
 */
@SuppressWarnings("all")
public class Sender {

	public static void main(String[] args) throws Exception {
		boolean openSSL = true;
		final String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S").format(new Date());
		// 发件人
		String address = "timor2020@yeah.net";
		// 发件人授权码
		String password = "TUTYSRVZFBQQIFPB";
		// 发件人姓名
		String name = "Jenkins";
		// 邮件主题
		String subject = "测试邮件";
		// 收件人
		String to = "981247127@qq.com";
		// 邮件内容
		String content = "<h1>来自 Java Mail 的邮件，今天没人听我讲课，好伤心，快哄哄我！</h1>";

		// SMTP 主机
		String host = "smtp.yeah.net";
		// SMTP 端口
		String port = openSSL ? "465" : "25";

		sendMessage(subject, content, address, password, name, to, null, null, host, port, null, openSSL);
	}

	/**
	 * @param subject         邮件标题
	 * @param content         邮件文本内容
	 * @param sender_address  发件人邮箱
	 * @param sender_password 发件人邮箱密码，QQ邮箱应为16位SMTP口令
	 * @param sender_name     发件人昵称
	 * @param to              收件人邮箱，多个收件人用","分隔
	 * @param cc              抄送人邮箱，多个抄送人用","分隔
	 * @param bcc             密送人邮箱，多个密送人用","分隔
	 * @param smtpHost        smtp服务器地址
	 * @param smtpPort        smtp服务器端口
	 * @param attachments     邮件附件绝对路径，多个附件用","分隔
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException:
	 * @Description: SMTP 发送邮件
	 */
	public static void sendMessage(String subject, String content, final String sender_address, final String sender_password, String sender_name, String to, String cc, String bcc, String smtpHost, String smtpPort, String attachments, boolean openSSL) throws MessagingException, UnsupportedEncodingException {
		//创建Properties类，用于记录邮箱的一些属性
		Properties props = new Properties();
		//表示SMTP发送邮件，必须进行身份验证
		props.put("mail.smtp.auth", "true");
		//SMTP服务器地址
		props.put("mail.smtp.host", smtpHost);
		//是否开启SSL
		if (!openSSL) {
			//SMTP服务器端口号
			props.put("mail.smtp.port", smtpPort);
		} else {
			//SMTP服务器ssl端口号
			props.setProperty("mail.smtp.socketFactory.port", smtpPort);
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}

		//构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				//发件人账号，发件人密码（QQ邮箱应为16位SMTP口令）
				return new PasswordAuthentication(sender_address, sender_password);
			}
		};

		//使用环境属性和授权信息，创建邮件会话
		Session session = Session.getInstance(props, authenticator);

		//创建邮件消息
		MimeMessage message = new MimeMessage(session);

		//设置发件人，有昵称时同时设置昵称
		try {
			String personal = sender_name == null || "".equals(sender_name) ? "anonymous" : sender_name;
			message.setFrom(new InternetAddress(sender_address, personal, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//设置一个或多个收件人
		message.setRecipients(RecipientType.TO, to);
		//设置一个或多个抄送人
		message.setRecipients(RecipientType.CC, cc);
		//设置一个或多个密送人
		message.setRecipients(RecipientType.BCC, bcc);

		//设置邮件标题
		message.setSubject(subject);

		//设置邮件的内容
		if (attachments == null || "".equals(attachments)) {
			//设置邮件的正文文本
			message.setContent(content, "text/html;charset=UTF-8");
		} else {
			//向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();

			//添加邮件文本内容
			BodyPart contentBodyPart = new MimeBodyPart();
			contentBodyPart.setContent(content, "text/html;charset=utf-8");
			multipart.addBodyPart(contentBodyPart);

			//添加邮件附件内容
			BodyPart attachmentBodyPart = new MimeBodyPart();
			String[] attachmentFiles = attachments.split(",");
			for (String attachmentFile : attachmentFiles) {
				if (attachmentFile != null && !"".equals(attachmentFile)) {
					attachmentBodyPart = new MimeBodyPart();

					//根据附件路径获取文件,
					FileDataSource dataSource = new FileDataSource(new File(attachmentFile));
					attachmentBodyPart.setDataHandler(new DataHandler(dataSource));

					//MimeUtility.encodeWord可以避免文件名乱码
					String strFileName = dataSource.getFile().getName();
					attachmentBodyPart.setFileName(MimeUtility.encodeText(strFileName));

					multipart.addBodyPart(attachmentBodyPart);
				}
			}

			//设置邮件的正文内容
			message.setContent(multipart);
		}

		//发送邮件
		Transport.send(message);
	}

}
